//
//  CYStatisticsContentVC.m
//  CreditAddressBook
//
//  Created by Lee on 15/6/30.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYStatisticsContentVC.h"
#import "TWRChart.h"
#import "CYCollectView.h"
#import "CYStatistics.h"
#import "CYDialTool.h"
#import "CYPerson.h"
#import "CYStatisticsTopView.h"
#import "CYDatabase.h"

@interface CYStatisticsContentVC ()

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UILabel *promptLabel;
@property (weak, nonatomic) IBOutlet UIButton *allBtn;

@property(strong, nonatomic) CYStatistics *stat;//统计模型
@property(strong, nonatomic) NSMutableArray *callRecords;
@property(strong, nonatomic) NSArray *points;//纵坐标
@property(strong, nonatomic) NSArray *names;//横坐标

@property(strong, nonatomic) UIButton *selectedBtn;

@property(strong, nonatomic) CYCollectView *collect;//总汇view
@property(strong, nonatomic) TWRChartView *chartView;//
//@property(strong, nonatomic) TWRChartView *pieView;//饼状图
@end

@implementation CYStatisticsContentVC

- (NSMutableArray *)callRecords {
    if (!_callRecords) {
        _callRecords = [NSMutableArray array];
    }
    return _callRecords;
}

//- (TWRChartView *)pieView {
//    if (!_pieView) {
//        _pieView = [[TWRChartView alloc] initWithFrame:CGRectMake(0, 140, 320, 300)];
//    }
//    return _pieView;
//}

- (TWRChartView *)chartView {
    if (!_chartView) {
        _chartView = [[TWRChartView alloc] initWithFrame:CGRectMake(0, 50, 320, 300)];
    }
    return _chartView;
}

- (CYCollectView *)collect {
    if (!_collect) {
        _collect = [CYCollectView collectView];
        _collect.width = CYScreeSize.width;
    }
    return _collect;
}

- (CYStatistics *)stat {
    if (!_stat) {
        _stat = [[CYStatistics alloc] init];
    }
    return _stat;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置基本属性
    [self setupProperty];
    
    //数据库加载数据
    
    //加载chart
    [self loadChart:CYIndexFirst];
    
}

- (void)setupProperty {
    self.promptLabel.hidden = YES;
    
    self.view.backgroundColor = [UIColor clearColor];
    self.scrollView.backgroundColor = [UIColor clearColor];
    //    self.scrollView.contentSize = [UIScreen mainScreen].bounds.size;
    
    //默认选中第一个
    [self selectedBtn:self.allBtn];
}

#pragma mark - 底部按钮点击
- (IBAction)tabBarClick:(UIButton *)sender {
    if (self.selectedBtn == sender) return;
    switch (sender.tag) {
        case CYIndexFirst:
            CYLog(@"全部");
            //加载chart
            [self loadChart:CYIndexFirst];
            break;
            
        case CYIndexSecond:
            CYLog(@"今天");
            //加载chart
            [self loadChart:CYIndexSecond];
            break;
            
        case CYIndexThird:
            CYLog(@"本周");
            //加载chart
            [self loadChart:CYIndexThird];
            break;
            
        case CYIndexFourth:
            CYLog(@"本月");
            //加载chart
            [self loadChart:CYIndexFourth];
            break;
            
        default:
            CYLog(@"全部");
            //加载chart
            [self loadChart:CYIndexFirst];
            break;
    }
    [self selectedBtn:sender];
}

- (void)loadChart:(NSInteger)index {
    if (self.person) {//个人统计
        //加载数据
        [self loadPersonData:index];
        if (self.callRecords && self.callRecords.count) {
            //若有通话记录
            self.topView.hidden = NO;
            self.promptLabel.hidden = YES;
//            self.pieView.hidden = YES;
            [self pieChart];
        } else {
            self.promptLabel.hidden = NO;
//            self.pieView.hidden = YES;
            self.topView.hidden = YES;
        }
    }else {//汇总统计
        switch (self.segmentIndex) {
            case CYIndexFirst:{//总汇
                //加载数据
                [self loadCollectData:index];
                //加载汇总view
                [self loadCollectView];
            }
                break;
                
            case CYIndexSecond://通话次数
                [self loadTimesData:index];
                [self barChart];
                break;
                
            case CYIndexThird://通话时长
                [self loadDurationData:index];
                [self barChart];
                break;
                
            default:
                break;
        }
        
    }
}

/**
 *  柱状图
 */
- (void)barChart {
    TWRChartView *chartView = self.chartView;
    chartView.backgroundColor = [UIColor clearColor];
    [self.scrollView addSubview:chartView];
    self.scrollView.contentSize = CGSizeMake(0, chartView.y + chartView.height);
    
    // Build chart data
    TWRDataSet *dataSet1 = [[TWRDataSet alloc] initWithDataPoints:self.points fillColor:[[UIColor orangeColor] colorWithAlphaComponent:0.5] strokeColor:[UIColor orangeColor]];
    
    TWRBarChart *bar = [[TWRBarChart alloc] initWithLabels:self.names dataSets:@[dataSet1] animated:YES];
    // Load data
    [chartView loadBarChart:bar];
    
}

/**
 *  饼状图
 */
- (void)pieChart {
    TWRChartView *chartView = nil;
    
    if (self.topView) {
        self.topView.statis = self.stat;
//        chartView = self.pieView;
        [self.scrollView addSubview:self.topView];
//        [self.scrollView addSubview:chartView];
        chartView.backgroundColor = [UIColor clearColor];
        
    }else {
        chartView = [[TWRChartView alloc] initWithFrame:CGRectMake(0, 0, 320, 300)];
        [self.scrollView addSubview:chartView];
        chartView.backgroundColor = [UIColor clearColor];
        self.scrollView.contentSize = CGSizeMake(0, chartView.y + chartView.height);
    }
    
    NSInteger times = self.stat.callRecord.callHistory.num - self.stat.callOutTimes;//未拨通次数
    
    NSArray *values = @[[NSNumber numberWithInteger:times], [NSNumber numberWithInteger:self.stat.callOutTimes]];
    
    UIColor *color1 = [UIColor redColor];
    UIColor *color2 = [UIColor colorWithHue:0.5 saturation:0.6 brightness:0.6 alpha:1.0];
    NSArray *colors = @[color1, color2];
    
    TWRCircularChart *pieChart = [[TWRCircularChart alloc] initWithValues:values colors:colors type:TWRCircularChartTypePie animated:YES];
    
    [chartView loadCircularChart:pieChart withCompletionHandler:^(BOOL finished) {
        if (finished) {
            
        }
    }];
    
    //    [self.view addSubview:chartView];//该方法放在此处不会生效？？
}

/**
 *  自定义总汇
 */
- (void)loadCollectView {
    self.collect.statistics = self.stat;
    self.scrollView.contentSize = CGSizeMake(0, self.collect.height);
    [self.scrollView addSubview:self.collect];
    
    _shareView = self.collect;//分享view
}

/**
 *  选中按钮
 */
- (void)selectedBtn:(UIButton *)btn {
    self.selectedBtn.selected = NO;
    btn.selected = YES;
    btn.tintColor = [UIColor clearColor];//去除系统默认选中后的背景色
    self.selectedBtn = btn;
}

#pragma mark - 总排行
/**
 *  汇总数据
 */
- (void)loadCollectData:(NSInteger)index {
    NSDictionary *totalparams = nil;
    NSDictionary *callOutParams = nil;
    NSDictionary *firstCallParams = nil;
    switch (index) {
        case CYIndexSecond:
            totalparams = @{@"queryDurationAndTimes": @YES, @"time": [CYDialTool timeWithStyle:CYTimeStyleDay]};
            callOutParams = @{@"queryComeOutDurationAndTimes": @YES};
            firstCallParams = @{@"timeAsc": @YES};
            break;
            
        case CYIndexThird:
            totalparams = @{@"queryDurationAndTimes": @YES, @"time": [CYDialTool timeWithStyle:CYTimeStyleWeek]};
            callOutParams = @{@"queryComeOutDurationAndTimes": @YES};
            firstCallParams = @{@"timeAsc": @YES};
            break;
            
        case CYIndexFourth:
            totalparams = @{@"queryDurationAndTimes": @YES, @"time": [CYDialTool timeWithStyle:CYTimeStyleMonth]};
            callOutParams = @{@"queryComeOutDurationAndTimes": @YES};
            firstCallParams = @{@"timeAsc": @YES};
            break;
            
        default:
            totalparams = @{@"queryDurationAndTimes": @YES};
            callOutParams = @{@"queryComeOutDurationAndTimes": @YES};
            firstCallParams = @{@"timeAsc": @YES};
            break;
    }
    NSArray *totalarr = [[CYDatabase sharedDatabase] callHistorysWithParam:totalparams];
    NSArray *callOutarr = [[CYDatabase sharedDatabase] callHistorysWithParam:callOutParams];
    self.stat.callRecord = totalarr.lastObject;
    CYCallRecord *callRecord = callOutarr.lastObject;
    self.stat.callOutDuration = callRecord.callDurationSum;
    self.stat.callOutTimes = callRecord.callHistory.num;
    CYCallRecord *firstCall = [[CYDatabase sharedDatabase] callHistorysWithParam:firstCallParams].firstObject;
    NSTimeInterval time = 0;
    if (firstCall.callHistory.createTime) {
        time = [NSDate date].timeIntervalSince1970 - firstCall.callHistory.createTime;
        self.stat.averageCallTimes = (time/self.stat.callRecord.callHistory.num)/3600;
        self.stat.averageCallDuration = [CYDialTool callTime:self.stat.callRecord.callHistory.durationSum/callRecord.callHistory.num];
    }
}

#pragma mark - 统计通话次数排行
/**
 *  通话次数排行数据
 */
- (void)loadTimesData:(NSInteger)index {
    NSDictionary *params = nil;
    switch (index) {
        case CYIndexSecond:
            params = @{@"orderByCallNum": @YES, @"time":[CYDialTool timeWithStyle:CYTimeStyleDay]};
            break;
            
        case CYIndexThird:
            params = @{@"orderByCallNum": @YES, @"time":[CYDialTool timeWithStyle:CYTimeStyleWeek]};
            break;
            
        case CYIndexFourth:
            params = @{@"orderByCallNum": @YES, @"time":[CYDialTool timeWithStyle:CYTimeStyleMonth]};
            break;
            
        default:
            params = @{@"orderByCallNum": @YES};
            break;
    }
    [self loadCallHistory:[NSMutableDictionary dictionaryWithDictionary:params]];
    self.points = [[self.callRecords valueForKey:@"callHistory"] valueForKeyPath:@"num"];
    self.names  = [self.callRecords valueForKeyPath:@"callName"];
    if (self.points.count > 5) {
        self.points = [self.points subarrayWithRange:NSMakeRange(0, 5)];
        self.names = [self.names subarrayWithRange:NSMakeRange(0, 5)];
    }
}

#pragma mark - 统计通话时长排行
/**
 *  通话时长数据
 */
- (void)loadDurationData:(NSInteger)index {
    NSDictionary *params = nil;
    switch (index) {
        case CYIndexSecond:
            params = @{@"orderByCallDuration": @YES, @"time":[CYDialTool timeWithStyle:CYTimeStyleDay]};
            break;
            
        case CYIndexThird:
            params = @{@"orderByCallDuration": @YES, @"time":[CYDialTool timeWithStyle:CYTimeStyleWeek]};
            break;
            
        case CYIndexFourth:
            params = @{@"orderByCallDuration": @YES, @"time":[CYDialTool timeWithStyle:CYTimeStyleMonth]};
            break;
            
        default:
            params = @{@"orderByCallDuration": @YES};
            break;
    }
    [self loadCallHistory:[NSMutableDictionary dictionaryWithDictionary:params]];
    
    self.points = [[self.callRecords valueForKey:@"callHistory"] valueForKey:@"durationSum"];
    self.names = [self.callRecords valueForKey:@"callName"];
    if (self.points.count > 5) {
        self.points = [self.points subarrayWithRange:NSMakeRange(0, 5)];
        self.names = [self.names subarrayWithRange:NSMakeRange(0, 5)];
    }
}

#pragma mark - 个人通话记录
/**
 *  个人通话记录统计
 */
- (void)loadPersonData:(NSInteger)index {
    NSDictionary *params = nil;
    switch (index) {
        case CYIndexSecond:
            params = @{@"phones": self.person.phones, @"time":[CYDialTool timeWithStyle:CYTimeStyleDay]};
            break;
            
        case CYIndexThird:
            params = @{@"phones": self.person.phones, @"time":[CYDialTool timeWithStyle:CYTimeStyleWeek]};
            break;
            
        case CYIndexFourth:
            params = @{@"phones": self.person.phones, @"time":[CYDialTool timeWithStyle:CYTimeStyleMonth]};
            break;
            
        default:
            params = @{@"phones": self.person.phones};
            break;
    }
    [self loadCallHistory:[NSMutableDictionary dictionaryWithDictionary:params]];
    if (!self.callRecords.count) return;
    //若有通话记录
    CYStatistics *personStat = [[CYStatistics alloc] init];
    personStat.callRecord = self.callRecords.firstObject;
    CGFloat durationSum = 0;
    int times = 0;
    //接通次数
    for (CYCallRecord *call in self.callRecords) {
        durationSum += call.callHistory.duration;
        if (call.callHistory.duration > .5) {
            times++;
        }
    }
    personStat.callRecord.callHistory.durationSum = durationSum;
    personStat.callRecord.callHistory.num = self.callRecords.count;
    CYCallRecord *last = self.callRecords.lastObject;
    personStat.averageCallTimes = ([NSDate date].timeIntervalSince1970 - last.callHistory.createTime)/self.callRecords.count/86400;
    personStat.callOutTimes = times;
    
    self.stat = personStat;
}

/**
 *  加载通话记录
 */
- (void)loadCallHistory:(NSMutableDictionary *)params {
    if (params[@"phones"]) {
        for (NSString *phone in params[@"phones"]) {
            params[@"phone"] = phone;
            NSArray *arr = [[CYDatabase sharedDatabase] callHistorysWithParam:params];
            if (arr && arr.count) {
                [self.callRecords addObjectsFromArray:arr];
            }
        }
    } else {
            NSArray *arr = [[CYDatabase sharedDatabase] callHistorysWithParam:params];
            [self.callRecords addObjectsFromArray:arr];
    }
    
}

- (NSString *)segmentTitle {
    return @"统计";
}

- (UIScrollView *)streachScrollView {
    return self.scrollView;
}

@end
